$(function () {

	//获取产品列表
    $.get("/stastics/getProList", function (re) {
        var proList = re.data;
        var proOptions = "<option value=''> 全部产品 </option>";
        for (var i in proList) {
            var pro = proList[i];
            proOptions += "<option value='" + pro.id + "'>" + pro.name + "</option>";
        }
        $("#product_list").html(proOptions);

    });

    var areaKey=[], scanData=[],userData=[];
    areaDate();
    areaDataDetail(1);

    $("#product_list").on("change",function(){
        areaDate();
        areaDataDetail(1);

        option. yAxis= [{type: 'value',name: '',axisLabel: {formatter: '{value}'}
            }];
        option.series= [{ name: '扫码量',type: 'bar',barWidth: 20,data: scanData},
            {name: '用户量',type: 'bar', barWidth: 20,data: userData }];

        myChart.setOption(option,true);
	});

    var myChart = echarts.init(document.getElementById("main"));
     var option = {
        title: {
            text: '基础指标趋势分析'
        },
        color:['#99FF00','#FFCC00'],
        tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            data: ['扫码量', '用户量'],
            align: 'auto',
            //right: 10
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areaKey
        }],
        yAxis: [{
            type: 'value',
            name: '',
            axisLabel: {
                formatter: '{value}'
            }
        }],
        series: [{
            name: '扫码量',
            type: 'bar',
            barWidth: 20,
            data: scanData
        }, {
            name: '用户量',
            type: 'bar',
            barWidth: 20,
            data: userData
        }]
    };

    //使用指定配置项和数据显示图表
    myChart.setOption(option);

    //数据导出
    $("#btn_export").click(function () {
        var productId = $("#product_list").val();
        //有数据时才能导出
        if($("#resultTotal_hidden").val() != 0){
            bootbox.bconfirm("确定是否导出？", function (re) {
                if (re) {
	            	 var url="/stastics/areaExport?productId="+productId;
                    window.open(url);
                }
            });
        }else{
            bootbox.balert("没有数据，无法导出!");
        }
    });

	//获取区域统计数据
	function areaDate() {
		var productId = $("#product_list").val();
        $.ajax({
            type: "get",
            url: "/stastics/getAreaData",
            cache:false,
            async:false,
			data:{productId:productId},
            dataType: "json",
            success: function(re){
                areaKey=[];
                scanData=[];
                userData=[];
                var data = re.data;
                if(data.length>0){
                    for (var i in data) {
                        var p = data[i];
                        if( p.poi_city.trim().length==0){
                            areaKey.push("未提供");
                        }else{
                            areaKey.push(p.poi_city);
                        }
                        scanData.push(p.scanData);
                        userData.push(p.openDate)
                    }
				}

            }
        });

    }

    function areaDataDetail(page){
        var productId = $("#product_list").val();

        page = page || 1;
        var  url ="/stastics/getAreaDataDetail?productId=" + productId + "&page=" +page;

        $.post(url, function (re) {
            var result = re.data, resultList=result.result;
            var str = "";
            for(var i=0; i<resultList.length; i++){
                var para = resultList[i];
                var poiCity=para.poi_city;
                if( poiCity.trim().length == 0){
                    poiCity="未提供"
                }
                str += '<tr>' +
                    '<td>'+poiCity +'</td>'+
                    '<td>'+ para.scanData + '</td>'+
                    '<td>'+ para.openDate + '</td>' +
                    '<td>'+ (para.scanData/(para.openDate == 0 ? 1: para.openDate)).toFixed(2) + '</td>' +
                    '<td>'+ para.prizeData + '</td>' +
                    '<td>'+ para.redData + '</td>' +
                    '<td>'+ (para.prizeData-para.redData) +'</td>' +
                '</tr>';
            }
            $('#tbody_data').html(str);
            resetPage(result.pageTotal, page);
            // $("#proTotal").text(result.resultTotal);

        });
    }

    //分页

    function resetPage(totalPage, currPage){
        var innerHTML = [];
        currPage = currPage || 1;
        innerHTML.push('<ul class="pagination pagination-sm no-margin">');
        if(currPage > 1){
            innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
        }
        if(currPage - 4 > 1){
            innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
        }
        for(var i = currPage - 3; i < currPage; i++){
            if(i > 1){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        innerHTML.push('<li class="active"><span>', currPage,'</span></li>')
        for(var i = currPage+1; i < currPage+3; i++){
            if(i < totalPage){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        if(currPage < totalPage - 3){
            innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
        }
        if(currPage < totalPage){
            innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
                '<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
        }
        innerHTML.push("</ul>")
        $("#page_model").data("total", totalPage).html(innerHTML.join(""));
    }

    $("#page_model").on("click", "li", function () {
        if($(this).hasClass("active")){
            return false;
        }
        var currPage = parseInt($("#page_model .active").text()),
            totalPage = $("#page_model").data("total");
        if($(this).hasClass("prev")){
            currPage--;
        } else if($(this).hasClass("next")){
            currPage++;
        } else if($(this).hasClass("bigPrev")){
            currPage -= 5;

            if(currPage < 1){
                currPage = 1;
            }
        } else if($(this).hasClass("bigNext")){
            currPage += 5;

            if(totalPage - currPage < 0){
                currPage = totalPage;
            }
        } else {
            currPage = parseInt($(this).text());
        }

        areaDataDetail(currPage);
    })
});